package com.dm.wallpaper.library.ablility.slice;

import com.dm.wallpaper.library.ResourceTable;
import com.dm.wallpaper.library.ablility.WallpaperBoardBrowserAbility;
import com.dm.wallpaper.library.database.DataProvider;
import com.dm.wallpaper.library.helpers.WallpaperHelper;
import com.dm.wallpaper.library.items.Category;
import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.preferences.Preferences;
import com.dm.wallpaper.library.utils.Log;
import com.dm.wallpaper.library.utils.*;
import com.dm.wallpaper.library.utils.Toast;
import com.dm.wallpaper.library.utils.Extras;
import com.dm.wallpaper.library.utils.SystemUtils;
import com.dm.wallpaper.library.utils.WallpaperDownloader;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.element.VectorElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextTool;
import ohos.agp.window.dialog.PopupDialog;
import ohos.app.Context;
import ohos.bundle.AbilityInfo;
import ohos.bundle.IBundleManager;
import ohos.media.image.PixelMap;
import ohos.miscservices.pasteboard.PasteData;
import ohos.miscservices.pasteboard.SystemPasteboard;
import ohos.miscservices.wallpaper.WallpaperController;
import ohos.utils.net.Uri;

import java.util.ArrayList;
import java.util.List;

import static com.dm.wallpaper.library.utils.SystemUtils.vp2px;
import static ohos.miscservices.wallpaper.WallpaperController.WALLPAPER_LOCK;
import static ohos.miscservices.wallpaper.WallpaperController.WALLPAPER_SYSTEM;

public class WallpaperBoardPreviewAbilitySlice extends AbilitySlice implements Component.ClickedListener, Component.LongClickedListener {

    private Image mPhotoView;
    private Text mNameText;
    private Text mAuthorText;
    private Image mMenuPreview;
    private Image mMenuSave;
    private Image mMenuApply;
    private Wallpaper mWallpaper;
    private TableLayout mTableLayout;
    private PopupDialog commonDialog;
    private DirectionalLayout mBottomPanel;
    private ScrollView tabScrollView;
    private TableLayout tabGrid;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_wallpaper_board_preview);
        int extraID = intent.getIntParam(Extras.EXTRA_LOCAL_ID, 0);
        mWallpaper = DataProvider.getInstance().getWallpaperByLocalIdID(extraID);

        initView();
    }

    private void initView() {
        mPhotoView = (Image) /*((StackLayout) findComponentById(ResourceTable.Id_stack_layout))
                .*/findComponentById(ResourceTable.Id_photo_view);
        mNameText = (Text) findComponentById(ResourceTable.Id_name);
        mAuthorText = (Text) findComponentById(ResourceTable.Id_author);
        mTableLayout = (TableLayout) findComponentById(ResourceTable.Id_tab_wallpaper_details);
        tabGrid = (TableLayout) findComponentById(ResourceTable.Id_tab_grid);
        mBottomPanel = (DirectionalLayout) findComponentById(ResourceTable.Id_bottom_panel);
        tabScrollView = (ScrollView) findComponentById(ResourceTable.Id_tab_scrollView);

        if (mWallpaper != null) {
            mNameText.setText(mWallpaper.getName());
            mAuthorText.setText(mWallpaper.getAuthor());
            // mPhotoView.setImageResource(mWallpaper.getLocalid());

            ImageLoader.getInstance().loadImage(mWallpaper.getUrl(), new SimpleImageLoadingListener() {
                @Override
                public void onLoadingComplete(String url, Component component, PixelMap pixelMap) {
                    mPhotoView.setPixelMap(pixelMap);
                }
            });

        }

        //TODO 三个按钮颜色
        mMenuPreview = (Image) findComponentById(ResourceTable.Id_menu_preview);
        mMenuSave = (Image) findComponentById(ResourceTable.Id_menu_save);
        mMenuApply = (Image) findComponentById(ResourceTable.Id_menu_apply);
        findComponentById(ResourceTable.Id_text_details).setClickedListener(this);
        findComponentById(ResourceTable.Id_left_mune_icon).setClickedListener(this);
        mMenuPreview.setClickedListener(this);
        mMenuPreview.setLongClickedListener(this);
        mMenuSave.setClickedListener(this);
        mMenuSave.setLongClickedListener(this);
        mMenuApply.setClickedListener(this);
        mMenuApply.setLongClickedListener(this);


        getUITaskDispatcher().delayDispatch(() -> {
            showTooltip();
        }, 1000);
    }

    private void showTooltip() {
        if (Preferences.get().isShowWallpaperTooltip()) {
            Tooltip mTooltip = Tooltip.Builder(this)
                    .to(mMenuPreview)
                    .content(ResourceTable.String_wallpaper_tooltip_preview)
                    .desc(ResourceTable.String_wallpaper_tooltip_preview_icon_tap)
                    .descIcon(ResourceTable.Graphic_svg_toolbar_preview_full)
                    .visibleDontShowAgain(true)
                    .cancelable(false)
                    .buttonCallback(tooltip -> {
                        Preferences.get().setShowWallpaperTooltip(!tooltip.getCheckboxState());
                        tooltip.dismiss();
                    })
                    .build();
            mTooltip.show();
        }
    }

    private void initWallpaperDetails() {
        if (mWallpaper == null) {
            return;
        }
        List<TabEntity> list = new ArrayList<>();
        List<Category> categoryList = new ArrayList<>();

        List<Category> categorys = DataProvider.getInstance().getCategorys();
        if (categorys != null) {
            categoryList.addAll(categorys);
        }
        list.add(new TabEntity(ResourceTable.Graphic_svg_toolbar_details_name, mWallpaper.getName(), "Name"));
        list.add(new TabEntity(ResourceTable.Graphic_svg_toolbar_details_author, mWallpaper.getAuthor(), "Author"));

        String dimensionsStr = mWallpaper.getDimensions().getWidth() + " x " + mWallpaper.getDimensions().getHeight() + " pixels";
        list.add(new TabEntity(ResourceTable.Graphic_svg_toolbar_details_dimensions, dimensionsStr, "Dimensions"));
        list.add(new TabEntity(ResourceTable.Graphic_svg_toolbar_details_format, WallpaperHelper.getFormat(mWallpaper.getMimeType()).toUpperCase(), "Format"));
        list.add(new TabEntity(ResourceTable.Graphic_svg_toolbar_details_size, WallpaperHelper.getSize(mWallpaper.getSize()), "Size"));
        list.add(TabEntity.emptyTabEntity());
        list.add(new TabEntity(ResourceTable.Graphic_svg_toolbar_details_palette, "Color Palette", "Color Palette"));
        list.add(TabEntity.emptyTabEntity());
        list.add(new TabEntity(ResourceTable.Graphic_svg_toolbar_details_palette_color, "#65D63d",  "Color"));
        list.add(new TabEntity(ResourceTable.Graphic_svg_toolbar_details_palette_color, "#2068D0", "Color"));
        list.add(new TabEntity(ResourceTable.Graphic_svg_collection_categories, "Category", "Category"));
        if (list.size() % 2 != 0) {
            list.add(TabEntity.emptyTabEntity());
        }

        mTableLayout.removeAllComponents();
        for (int i = 0; i < list.size(); i++) {
            TabEntity tabEntity = list.get(i);
            Component component = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_wallpaper_details_layout, null, false);
            component.setTag(tabEntity);
            ComponentContainer.LayoutConfig layoutConfig = component.getLayoutConfig();
            layoutConfig.width = SystemUtils.getDisplayWidthInPx(this) / 2;
            Image image_tab = (Image) component.findComponentById(ResourceTable.Id_image_tab);
            Text text_tab = (Text) component.findComponentById(ResourceTable.Id_text_tab);
            component.setClickedListener(component1 -> {
                String title = tabEntity.title;
                if (TextTool.isNullOrEmpty(title)) {
                    return;
                }
                if (!tabEntity.type.equals("Color Palette") && !tabEntity.type.equals("Category")) {
                    if (tabEntity.type.equals("Color")) {
                        DialogUtils.getInstance().showToastBottom(this, new Toast.InitToastLayout() {
                            @Override
                            public Component initToastLayout(Context context) {
                                Component component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_toast_open, null, false);
                                ((Text) component.findComponentById(ResourceTable.Id_content)).setText(tabEntity.type + ":" + title);
                                ((Text) component.findComponentById(ResourceTable.Id_open)).setText("COPY");

                                Component contentLayout = component.findComponentById(ResourceTable.Id_content_layout);
                                contentLayout.setBackground(Toast.buildDrawableByColorRadius(Color.getIntColor("#70000000"), vp2px(context, 20)));
                                component.findComponentById(ResourceTable.Id_open).setClickedListener(o -> {
                                    SystemPasteboard systemPasteboard = SystemPasteboard.getSystemPasteboard(getContext());
                                    PasteData pasteData = new PasteData();
                                    pasteData.addTextRecord(title);
                                    systemPasteboard.setPasteData(pasteData);
                                });
                                return component;
                            }
                        });
                    } else {
                        Toast.show(this, tabEntity.type + ":" + title, LayoutAlignment.BOTTOM);
                    }
                }
            });
            if (tabEntity.placeholder) {
                text_tab.setVisibility(Component.VERTICAL);
                image_tab.setVisibility(Component.VERTICAL);
            } else {
                text_tab.setText(tabEntity.title);
                VectorElement vectorElement = new VectorElement(this, tabEntity.image);


                image_tab.setImageElement(vectorElement);
                component.setLayoutConfig(layoutConfig);
                text_tab.setVisibility(Component.VISIBLE);
                image_tab.setVisibility(Component.VISIBLE);
            }
            mTableLayout.addComponent(component);
        }
//        //添加一个
        tabGrid.removeAllComponents();
        if (!categoryList.isEmpty()) {
//            ListContainer listContainer = new ListContainer(this);
//            TableLayout.LayoutConfig layoutConfig = new TableLayout.LayoutConfig();
//            layoutConfig.width = TableLayout.LayoutConfig.MATCH_PARENT;
//            layoutConfig.height = TableLayout.LayoutConfig.MATCH_CONTENT;
//            listContainer.setLayoutConfig(layoutConfig);
//            WallpaperDetailsCategoryAdapter categoriesListAdapter = new WallpaperDetailsCategoryAdapter(this, categoryList);
//            listContainer.setItemProvider(categoriesListAdapter);
//            mTableLayout.addComponent(listContainer);

            for (int i = 0; i < categoryList.size(); i++) {
                Category category = categoryList.get(i);
                Component component = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_wallpaper_details_category_layout, null, false);
                ComponentContainer.LayoutConfig layoutConfig = component.getLayoutConfig();
                int vp1 = (int) SystemUtils.vp2px(this, 10);
                int vp2 = (int) SystemUtils.vp2px(this, 5);
                layoutConfig.width = SystemUtils.getDisplayWidthInPx(this) / 2 - vp1 - vp2;
                component.setMarginsTopAndBottom(vp2, vp2);
                if (i % 2 == 0) {
                    component.setMarginsLeftAndRight(vp1, vp2);
                } else {
                    component.setMarginsLeftAndRight(vp2, vp1);
                }
                component.setTag(category);
                Text tvTitle = (Text) component.findComponentById(ResourceTable.Id_tv_title);
                Image image = (Image) component.findComponentById(ResourceTable.Id_iv_image);
                image.setCornerRadius(SystemUtils.vp2px(this, 15));
                //TODO 设置图片
//                image.setImageAndDecodeBounds(category.getLocalid());
                ImageLoader.getInstance().displayImage(category.getThumbUrl(), image);
                tvTitle.setText(category.getName());

                component.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        Intent getIntent = new Intent();
                        Operation opt = new Intent
                                .OperationBuilder()
                                .withBundleName(getBundleName())
                                .withAbilityName(WallpaperBoardBrowserAbility.class)
                                .build();
                        getIntent.setOperation(opt);
                        Log.i("WallpaperBoardPreviewAbilitySlice.onClick([component]):219      " + category.getName() + "     " + category.getCount());
                        getIntent.setParam(Extras.EXTRA_CATEGORY, category.getName());
                        getIntent.setParam(Extras.EXTRA_COUNT, category.getCount());
                        getIntent.setParam(Extras.EXTRA_FRAGMENT_ID, Extras.ID_CATEGORY_WALLPAPERS);
                        WallpaperBoardPreviewAbilitySlice.this.startAbility(getIntent);
                    }
                });

                tabGrid.addComponent(component);
            }
        }
    }


    @Override
    public void onClick(Component component) {
        int id = component.getId();
        if (id == ResourceTable.Id_menu_preview) {
            //展示详情页


        } else if (id == ResourceTable.Id_menu_save) {
            download(mWallpaper);
        } else if (id == ResourceTable.Id_menu_apply) {
            DialogUtils.getInstance().showDialog(component, mWallpaper, false);
        } else if (id == ResourceTable.Id_text_details) {
            boolean isExpand = mTableLayout.getVisibility() == Component.VISIBLE;
            setBottomPanel(!isExpand);
        } else if (id == ResourceTable.Id_left_mune_icon) {
            terminateAbility();
        }
    }

    @Override
    public void onLongClicked(Component component) {
        int id = component.getId();
        int res = 0;
        if (id == ResourceTable.Id_menu_preview) {

            res = ResourceTable.String_wallpaper_preview_full;
        } else if (id == ResourceTable.Id_menu_save) {
            res = ResourceTable.String_wallpaper_save_to_device;
        } else if (id == ResourceTable.Id_menu_apply) {
            res = ResourceTable.String_wallpaper_apply;
        }
        if (res == 0) return;
        Toast.showShort(this, res);
    }

    private void setBottomPanel(boolean expand) {
        double maxHeight = SystemUtils.getDisplayHightInPx(this) * 0.9;
        double mimHeight = SystemUtils.vp2px(this, 150);
        if (expand) {
            mAuthorText.setVisibility(Component.HIDE);
            mNameText.setVisibility(Component.HIDE);
            mTableLayout.setVisibility(Component.VISIBLE);
            tabScrollView.setVisibility(Component.VISIBLE);
            //mBottomPanel.setHeight((int) ();
            ShapeElement shapeElement = new ShapeElement();
            RgbColor RgbColor = new RgbColor(255, 255, 255, 255);
            shapeElement.setRgbColor(RgbColor);
            mBottomPanel.setBackground(shapeElement);
            AnimatorValue animatorValue = new AnimatorValue();
            animatorValue.setLoopedCount(0);
            animatorValue.setDuration(200);
            animatorValue.setValueUpdateListener((animatorValue1, v) -> {
                ComponentContainer.LayoutConfig layoutConfig = mBottomPanel.getLayoutConfig();
                int height = Math.max((int) (maxHeight * v), (int) mimHeight);
                layoutConfig.height = height;
                layoutConfig.width = ComponentContainer.LayoutConfig.MATCH_PARENT;
                mBottomPanel.setLayoutConfig(layoutConfig);
            });
            animatorValue.start();
            initWallpaperDetails();
        } else {
            mAuthorText.setVisibility(Component.VISIBLE);
            mNameText.setVisibility(Component.VISIBLE);
            mTableLayout.setVisibility(Component.HIDE);
            tabScrollView.setVisibility(Component.HIDE);
            mBottomPanel.setHeight((int) mimHeight);
            ShapeElement shapeElement = new ShapeElement();
            RgbColor RgbColor = new RgbColor(0, 0, 0, 102);
            shapeElement.setRgbColor(RgbColor);
            mBottomPanel.setBackground(shapeElement);
        }
    }


    private void download(Wallpaper wallpaper) {
        if (wallpaper == null) {
            return;
        }

        boolean p1 = verifySelfPermission("ohos.permission.READ_USER_STORAGE") == IBundleManager.PERMISSION_GRANTED;
        boolean p2 = verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") == IBundleManager.PERMISSION_GRANTED;
        boolean p3 = verifySelfPermission("ohos.permission.WRITE_MEDIA") == IBundleManager.PERMISSION_GRANTED;
        boolean p4 = verifySelfPermission("ohos.permission.READ_MEDIA") == IBundleManager.PERMISSION_GRANTED;
        if (p1 && p2 && p3 && p4) {
            //开始下载
            WallpaperDownloader.prepare(this).wallpaper(wallpaper).start();
        } else {
            boolean c = canRequestPermission("ohos.permission.WRITE_USER_STORAGE");
            if (c) {
                String[] per = {"ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_MEDIA",
                        "ohos.permission.READ_MEDIA", "ohos.permission.WRITE_USER_STORAGE"};
                requestPermissionsFromUser(per, 1000);
            } else {
                String promission = SystemUtils.getString(this, ResourceTable.String_permission_storage_denied);
                Log.i("LatestListProvider.download([wallpaper]):138    " + promission);
                Toast.show(this, promission);
            }
        }
    }


    public static class TabEntity {
        int image;
        String title;
        boolean placeholder;
        String type;

        public static TabEntity emptyTabEntity() {
            TabEntity tabEntity = new TabEntity();
            tabEntity.placeholder = true;
            return tabEntity;
        }

        public TabEntity() {
        }

        public TabEntity(int image, String title, String type) {
            this.image = image;
            this.title = title;
            this.type = type;
        }

    }
}
